<template>
  <div class="device-list">
    <CommTitle :title="title" class="left-card-one" />
    <table class="device-list-table left-card-two">
      <thead>
        <tr class="table-th">
          <th>序号</th>
          <th>设备</th>
          <th>状态</th>
        </tr>
      </thead>

      <tbody ref="tableRef" @mouseover="stopScroll" @mouseleave="startScroll">
        <tr
          v-for="(item, index) in filterDeviceList"
          :key="index"
          :data-index="index"
          :class="[index % 2 === 0 ? 'even-bg' : '', item.modelId === currentListItem?.modelId ? 'active-tr' : '']"
          @click="openDeviceInfo(item)"
        >
          <td>{{ index + 1 }}</td>
          <el-tooltip
            :hide-after="0"
            popper-class="atooltip"
            placement="top"
            raw-content
            :content="insertLineBreaks(item.deviceName)"
          >
            <td>{{ item.deviceName }}</td>
          </el-tooltip>
          <td>
            {{ item.deviceStatus === 'true' ? '在线' : '离线' }}
            <span
              class="state"
              :style="{ backgroundColor: item.deviceStatus === 'true' ? '#3bff63' : '#97a4ad' }"
            ></span>
          </td>
        </tr>
      </tbody>
      <!-- <p v-else>暂无设备数据..</p> -->
      <DeviceInfo ref="deviceInfoRef" @clearListItem="clearCurrentListItem()" />
    </table>
  </div>
</template>

<script setup>
import { onMounted, watch, ref, nextTick, computed, onBeforeUnmount, toRefs } from 'vue'
import CommTitle from './CommTitle.vue'
import DeviceInfo from './DeviceInfo.vue'
import { ArmData } from '@/views/data/DeviceData.js'
import XJPostionData from '@/views/data/XJPostionData.js'
import { useStore } from 'vuex'
const store = useStore()
const { currentRegionName, deviceListId, deviceList, infoFuzzy } = toRefs(store.state)

const props = defineProps({
  title: {
    type: String,
    default: '设备列表'
  }
  // deviceList: {
  //   type: Array,
  //   // require: true,
  //   default: () => {
  //     return [
  //       // { deviceName: '设备1', devicestate: '在线' },
  //       // { deviceName: '设备2', devicestate: '离线' },
  //       // { deviceName: '设备3', devicestate: '在线' },
  //       // { deviceName: '设备4', devicestate: '在线' }
  //     ]
  //   }
  // },
  // infoFuzzy: { // 所有型架在线工位
  //   type: Array,
  //   default: () => []
  // }
})

// #region  列表滚动
let scrollInterval = null
const tableRef = ref(null)
function startScroll () {
  stopScroll()
  scrollInterval = setInterval(scroll, 60)
}
function stopScroll () {
  // console.log('销毁滚动')

  scrollInterval && clearInterval(scrollInterval)
  scrollInterval = null
}
document.addEventListener('keydown', e => {
  if (e.key === 'p') {
    if (scrollInterval !== null && scrollInterval !== undefined) {
      console.log('定时器正在运行')
    } else {
      console.log('定时器已停止')
    }
  }
})

function scroll () {
  if (!deviceList.value.length) return
  if (!tableRef.value) return
  if (currentListItem.value) return
  tableRef.value.scrollTop += 1

  const ListHeight = tableRef.value.clientHeight
  // console.log('实际高度', tableRef.value.scrollHeight)
  // console.log('元素高度', ListHeight)
  // console.log('已经滚动高度', tableRef.value.scrollTop)
  // console.log('窗口大小', (tableRef.value.scrollHeight - ListHeight))

  if (tableRef.value.scrollTop + 10 >= tableRef.value.scrollHeight - ListHeight) {
    const childrens = tableRef.value.children
    const dom = childrens[0]
    const maxDomNum = Math.ceil(ListHeight / dom.clientHeight)

    if (childrens.length > maxDomNum) {
      // tableRef.value.removeChild(dom)
      // 根据奇偶行添加背景色,并且有背景色则是删除背景色
      if (childrens[childrens.length - 1].classList.contains('even-bg')) {
        dom.classList.remove('even-bg')
      } else {
        dom.classList.add('even-bg')
      }
      tableRef.value.append(dom)
    }
  }
}
function resetScroll () {
  if (tableRef.value && deviceList.value.length) {
    nextTick(() => {
      deviceInfoRef.value?.close()
      stopScroll()
      console.log('重置滚动列表')
      tableRef.value.scrollTop = 0
      // 重置DOM顺序
      resetDomIndex()
      startScroll()
    })
  }
}
function insertLineBreaks (text) {
  let result = '<span>'
  for (let i = 0; i < text.length; i += 20) {
    result += `${text.slice(i, i + 20)}<br />`
  }
  result.slice(0, -6)

  return (result += '<span>')
}
// #endregion

const deviceInfoRef = ref(null)
const currentListItem = ref(null)

function openDeviceInfo (item) {
  store.commit('setDeviceListId', item.modelId)
  currentListItem.value = item
  deviceInfoRef.value.open(item)
}
function clearCurrentListItem () {
  store.commit('setDeviceListId', '')
  currentListItem.value = null
}

// #region  自动过滤设备列表
function getXJByRegionName () {
  // 获取该区域上的在架型架
  const result = XJPostionData.filter(item => item.region === currentRegionName.value).map(item => item.stationName)
  // console.log('result', result)

  const xjIndex = infoFuzzy.value
    .filter(item => {
      const deviceState = JSON.parse(item.collectValue)['型架当前位置']
      // console.log('deviceState', deviceState)
      return result.some(name => deviceState.includes(name))
    })
    .map(item => 'P' + String(item.modelId.match(/(\d+)$/)[0]).padStart(2, '0'))
  // console.log('编号', xjIndex)
  return xjIndex
}
const filterDeviceList = computed(() => {
  if (!currentRegionName.value) {
    console.log('在车间内')
    return deviceList.value
  } else {
    console.log('在区域内')
    const areaSet = new Set()
    ArmData.forEach(item => {
      if (item.belongArea === currentRegionName.value) {
        areaSet.add(item.id.split('-')[1])
      }
    })
    // 查找型架
    const xjIndex = getXJByRegionName()
    // console.log('xjIndex', areaSet, xjIndex, deviceList.value)

    const result = deviceList.value.filter(
      item =>
        !item.deviceName.includes('AGV') &&
        (xjIndex.some(index => item.equipId.includes(index)) || // 过滤型架
          [...areaSet].some(area => item.modelId.includes(area)) || // 过滤机械臂
          (currentRegionName.value === '总装站位' && item.deviceName.includes('总装站位定位器'))) // 要总装站位上的定位器
    )

    nextTick(() => {
      if (result.length === filterDeviceList.value.length) return // 防止列表长度不变时数据更新，列表被重置
      if (tableRef.value && result.length) {
        console.log('重置区域列表')

        resetDomIndex()
      }
    })
    return result
  }
})
function resetDomIndex () {
  // 重置DOM顺序
  const children = [...tableRef.value.children]
  children.sort((a, b) => {
    const aIndex = parseInt(a.getAttribute('data-index'))
    const bIndex = parseInt(b.getAttribute('data-index'))
    return aIndex - bIndex
  })

  // 重新按原始顺序添加DOM元素
  children.forEach(child => {
    tableRef.value.appendChild(child)
  })
}
// #endregion

onMounted(async () => {
  nextTick(() => {
    startScroll()
  })
  watch(() => currentRegionName, () => {
    resetScroll()
  },
  { deep: true, immediate: true }
  )

  watch(() => deviceListId, () => {
    // 高亮选中的设备列表信息
    if (deviceListId.value) {
      const index = filterDeviceList.value.findIndex(item => item.modelId === deviceListId.value)

      if (index > -1) {
        // console.log('找到', index)
        openDeviceInfo(filterDeviceList.value[index])
        // 根据findItem列表下标位置，使列表滚动当前位置
        if (tableRef.value) {
          nextTick(() => {
            if (tableRef.value && filterDeviceList.value.length) {
              resetDomIndex()
              const rows = tableRef.value.children
              // 这里能不能再加一些判断，若在当前可视区域内就滚动

              if (rows.length > index) {
                // tableRef.value.scrollTop = rows[index].offsetTop - tableRef.value.offsetTop
                const rowTop = rows[index].offsetTop - tableRef.value.offsetTop
                const rowBottom = rowTop + rows[index].offsetHeight
                const viewTop = tableRef.value.scrollTop
                const viewBottom = viewTop + tableRef.value.clientHeight

                // 如果行不在可视区域内才滚动
                if (rowTop < viewTop || rowBottom > viewBottom) {
                  tableRef.value.scrollTop = rowTop
                }
              }
            }
          })
        }
      }
    } else {
      deviceInfoRef.value?.close()
    }
  },
  { deep: true }
  )
})
onBeforeUnmount(() => {
  stopScroll()
})
</script>

<style lang="less">
.device-list {
  height: 50%;
  display: flex;
  flex-direction: column;
  .device-list-table {
    height: calc(100% - 60px);
    box-sizing: border-box;
    padding-left: 10px;
    padding-right: 10px;
    padding-bottom: 10px;
    // background-color: rgba(255, 0, 0, 0.525);
    display: flex;
    flex-direction: column;

    thead {
      tr {
        font-family: Source Han Sans CN;
        font-size: 14px;
        color: rgba(255, 255, 255, 0.6);
        display: flex;
        margin-bottom: 5px;
        th {
          &:nth-child(1) {
            width: 10%;
          }
          &:nth-child(2) {
            width: 50%;
          }
          &:nth-child(3) {
            width: 40%;
          }
        }
      }
    }

    tbody {
      flex: 1;
      // height: 97%;
      font-family: Source Han Sans CN;
      overflow-y: scroll;
      &::-webkit-scrollbar {
        display: none;
        // width: 0;
      }
      // background-color: red;

      tr {
        display: block;
        height: 36px;
        margin-bottom: 4px;
        line-height: 36px;
        &.even-bg {
          background: url('@/assets/homePage/row.png') no-repeat;
          background-size: 100% 100%;
          transition: background 0.3s ease-in-out; /* 添加过渡效果 */
        }
        &:hover {
          background: url('@/assets/homePage/row-hover.png') no-repeat;
          background-size: 100% 100%;
        }

        td {
          display: inline-block;
          font-size: 12px;
          color: #ffffff;
          box-sizing: border-box;
          padding: 0 4px;
          text-align: center;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          // width: 200%;
          &:nth-child(1) {
            width: 10%;
          }
          &:nth-child(2) {
            width: 50%;
          }
          &:nth-child(3) {
            width: 40%;
            // position: relative;
            > span {
              vertical-align: middle;
              margin-bottom: 3px;
              margin-left: 5px;
              // position: absolute;
              // top: 10px;
              display: inline-block;
              width: 14px;
              height: 14px;
              border-radius: 50%;
            }
          }
        }
      }
      .active-tr {
        background: url('@/assets/homePage/row-hover.png') no-repeat !important;
        background-size: 100% 100% !important;
      }
    }
  }
}
</style>
